import { Modal } from "@arco-design/web-react";
import { useEffect, useRef, useState } from "react";
import { useSelector } from "react-redux";

import MBProtocalFactory from '../../../sdk/module/mb_constants'
import IMSDK from '../../../sdk'
import uuid from "../../../sdk/module/uuid";
import { MessageType } from "../../../domain/im/entity";
import { off } from "process";




export const WebRtcModel: React.FC<any> = () => {

    // remote local
    const [mainVideo, setMainVideo] = useState('local');

    const [localStream, setLocalStream] = useState<any>(null);
    const [remoteStream, setRemoteStream] = useState<any>(null);
    const [peerConnection, setPeerConnection] = useState<any>(null);
    const { videoUserId, visible, call } = useSelector((state: any) => state.user.value);

    const remoteVideoRef = useRef<any>(null);
    const localVideoRef = useRef<any>(null);


    const { candidate } = useSelector((state: any) => state.user.value);

    const { offer } = useSelector((state: any) => state.user.value);

    const { answer } = useSelector((state: any) => state.user.value);

    const streamInitializedRef = useRef(false);

    const toggleMainVideo = () => {
        setMainVideo(mainVideo === 'local' ? 'remote' : 'local');
    };
   




    useEffect(()=>{
        if (remoteVideoRef.current && remoteStream) {
            console.log('渲染视频',remoteStream)
            // remoteVideoRef.current.srcObject = remoteStream;
            remoteVideoRef.current.src = "https://lf3-static.bytednsdoc.com/obj/eden-cn/gfeeh7pldnupqps/novel/welcome.mp4";
            remoteVideoRef.current.play(); // 确保视频开始播放
        }

    },[remoteStream])

    

    useEffect(()=>{
        if (answer && peerConnection) {
            console.log('收到应答answer')
            const str = answer.dataContent;
            const newAnswer = JSON.parse(str);
            peerConnection.setRemoteDescription( new RTCSessionDescription(newAnswer))
            .then(() => {
                console.log('远程描述设置成功');
                // 这里可以添加额外的逻辑，比如开始播放远程流
            })
            .catch((error:any) => {
                console.error('设置远程描述失败:', error);
            });
        
        }

    },[answer])

    useEffect(()=>{
        if (offer && peerConnection) {
            console.log('收到新的收到offer')
            const str = offer.dataContent;
            const newOffer = JSON.parse(str);
            peerConnection.setRemoteDescription(new RTCSessionDescription(newOffer))
            .then(() => {
                return peerConnection.createAnswer();
            })
            .then((answer:any) => {
                return peerConnection.setLocalDescription(answer);
            })
            .then(() => {
               const answer =  JSON.stringify(peerConnection.localDescription);
                console.log('已经收到对方的offer',offer);
                console.log("我已经应答",answer)
                let p: any = MBProtocalFactory.createCommonData({
                    dataContent: answer,
                    from: IMSDK.getLoginInfo().loginUserId,
                    fp: uuid.v1(),
                    QoS: true,
                    to: videoUserId,
                    typeu: MessageType.VideoAnswer
                });
                IMSDK.sendData(p);
            })
            .catch((error:any) => {
                console.error('Error handling offer', error);
            });
        
        }

    },[offer])


    useEffect(() => {
        if (candidate && peerConnection) {
            console.log('收到新的收到candidate')
            const str = candidate.dataContent;
            const obj = JSON.parse(str);
            console.log(obj);
            peerConnection.addIceCandidate(new RTCIceCandidate(obj));        
        }
    }, [candidate, peerConnection])


    useEffect(() => {
        console.log(visible && videoUserId && call && !streamInitializedRef.current)
        if (visible && videoUserId && call) {
            navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then((stream: any) => {
                setLocalStream(stream);
                streamInitializedRef.current = true; // 设置为true，防止重复初始化

                localVideoRef.current.srcObject = stream;
                localVideoRef.current.play(); // 确保视频开始播放


                // // 临时使用
                // remoteVideoRef.current.srcObject = stream;
                // remoteVideoRef.current.play(); // 确保视频开始播放

                
                 // 创建 RTCPeerConnection
                const pc = new RTCPeerConnection();
                setPeerConnection(pc);

                pc.onicecandidate = event => {
                    if (event.candidate) {
                        console.log('New ICE candidate:', event.candidate);
                        let p: any = MBProtocalFactory.createCommonData({
                            dataContent: JSON.stringify(event.candidate),
                            from: IMSDK.getLoginInfo().loginUserId,
                            fp: uuid.v1(),
                            QoS: true,
                            to: videoUserId,
                            typeu: MessageType.Candidate
                        });
                        IMSDK.sendData(p);

                    }
                };
                
                // 添加本地流到 RTCPeerConnection
                stream.getTracks().forEach((track:any) => pc.addTrack(track, stream));
               
                pc.ontrack = event => {
                    console.log("收到对方的视频流")
                    if (event.streams && event.streams[0]) {
                        setRemoteStream(event.streams[0]);
                    } else {
                        const inboundStream = new MediaStream();
                        inboundStream.addTrack(event.track);
                        setRemoteStream(inboundStream);
                    }

                    
                };

                if (call == "recipient") {


                    
                    
                    pc.createOffer().then((offer)=> {
                        pc.setLocalDescription(offer)
                        console.log("我的Offer ",offer)
                        let p: any = MBProtocalFactory.createCommonData({
                            dataContent: JSON.stringify(offer),
                            from: IMSDK.getLoginInfo().loginUserId,
                            fp: uuid.v1(),
                            QoS: true,
                            to: videoUserId,
                            typeu: MessageType.VideoOffer
                        });
                        IMSDK.sendData(p);
                    })
                    .catch(error => console.error('Error setting local description', error));
                }

               
            })

            return () => {
                if (localStream) {
                    localStream.getTracks().forEach((track: any) => track.stop());
                }

                if (peerConnection) {
                    peerConnection.close();
                }
            };
        }
    }, [visible, videoUserId, call])

    const mainCss = 'object-cover w-[350px] h-[600px]';
    const minCss = 'overflow-hidden rounded-2xl  absolute top-3 left-3 object-cover w-[100px] h-[180px] cursor-pointer';
    return <>
        <Modal
            style={{ boxShadow: '0px 2px 10px rgba(0, 0, 0, 0.10)' }}
            className={`"shadow-2xl w-[350px] h-[600px] rounded-xl overflow-hidden"`}
            title={null}
            alignCenter={false}
            mask={true}
            visible={visible}
            footer={null}
            closeIcon={null}
            autoFocus={false}
            focusLock={false}
        >

            <div className="relative shadow-2xl w-[350px] h-[600px] rounded-xl overflow-hidden ">
                <video className={mainVideo == "local" ? mainCss : minCss} autoPlay playsInline muted ref={localVideoRef}></video>
                <video onClick={toggleMainVideo} className={mainVideo == "local" ? minCss :mainCss } autoPlay playsInline muted ref={remoteVideoRef}></video> 
                <div className="absolute bottom-8 w-[350px] h-[50px] flex flex-row justify-center items-center">
                    <button className="bg-red-500 text-white w-[60px] h-[60px] text-center rounded-full "> 挂断</button>
                </div>
                 </div>
        </Modal>

    </>
}